<template>
  <div>
    <el-card class="!border-none" shadow="never">
      <el-page-header
        :content="route.query.id ? '编辑商品' : '新增商品'"
        @back="$router.back()"
      />
    </el-card>
    <el-card class="!border-none mt-4" shadow="never">
      <el-form
        :inline="true"
        :model="formData"
        label-width="120px"
        class="w-[100%]"
        :rules="goodRule"
        ref="formRef"
      >
        <el-form-item label="所属分类" prop="second_cat_id">
          <el-tree-select
              :props="{ children: 'child_cats', label: 'name', value: 'id' }"
              class="flex-1"
              v-model="formData.second_cat_id"
              :data="optionsData.lists.list"
              clearable
              :default-expand-all="true"
              placeholder="请选择分类"
          />
        </el-form-item>
        <div>
          <el-form-item label="商品名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入等级名称" />
          </el-form-item>
        </div>

       <div>
         <el-form-item label="商品封面" prop="cover">
           <div>
               <el-image v-if="formData.cover" style="width: 100px; height: 100px" :src="formData.cover" />
<!--             <material-picker :limit="9" v-model="formData.slider" />-->
               <upload
                       v-if="!formData.cover || route.query.id"
                       class="mr-3"
                       :type="'image'"
                       :show-progress="true"
                       @change="actionImg('cover')"
                       ref="coverRef"
               >
                   <el-button type="primary">本地上传</el-button>
               </upload>
           </div>
         </el-form-item>
       </div>
       <div>
         <el-form-item label="商品轮播图" prop="slider">
           <div>
               <template v-for="item in formData.slider" v-if="formData.slider.length < 9">
                   <el-image style="width: 100px; height: 100px; margin-right: 4px" :src="item" />
               </template>
<!--             <material-picker :limit="9" v-model="formData.slider" />-->
               <upload
                   class="mr-3"
                   :type="'image'"
                   :show-progress="true"
                   @change="actionImg('slider')"
                   ref="imgRef"
               >
                   <el-button type="primary">本地上传</el-button>
               </upload>
             <div class="form-tips">
               建议尺寸：800*800,可拖拽改变图片顺序，默认首张图为主图，最多可上传9张
             </div>
           </div>
         </el-form-item>
       </div>
        <div>
<!--          <el-form-item label="商品市场价" prop="price_market">-->
<!--            <el-input-number v-model="formData.price_market" :min="0" :precision="2" :step="0.1" controls-position="right"/>-->
<!--          </el-form-item>-->
          <el-form-item label="鸡蛋数量" prop="price_selling">
            <el-input-number v-model="formData.price_selling" :min="0" controls-position="right"/>
          </el-form-item>
<!--          <el-form-item label="成本价(供货商价格)" prop="vip_reward_balance2" label-width="150px">-->
<!--            <el-input-number v-model="formData.vip_reward_balance2" :min="0" :precision="2" :step="0.1" controls-position="right"/>-->
<!--          </el-form-item>-->
            <el-form-item label="商品库存" prop="stock_total">
                <el-input-number v-model="formData.stock_total" :min="0" :step="1"  controls-position="right"/>
            </el-form-item>
            <el-form-item label="商品限购数量" prop="limit_max_num">
                <el-input-number v-model="formData.limit_max_num" :min="0" controls-position="right"/>
            </el-form-item>
            <el-form-item label="虚拟销量" prop="stock_virtual">
                <el-input-number v-model="formData.stock_virtual" :min="0" controls-position="right"/>
            </el-form-item>
        </div>
        <div>
          <el-form-item label="可见范围">
              <el-radio-group v-model="formData.daili_viewable_radio">
                  <el-radio :label="1">全部可见</el-radio>
                  <el-radio :label="2">固定代理可见</el-radio>
                  <el-radio :label="3">固定代理不可见</el-radio>
              </el-radio-group>
          </el-form-item>
            <el-form-item v-if="formData.daili_viewable_radio == 2" label="哪些代理可见" prop="viewable">
                <el-input v-model="formData.viewable" placeholder="请输入哪些代理可见">
                    <template #append>以英文,分隔开</template>
                </el-input>
            </el-form-item>
            <el-form-item v-if="formData.daili_viewable_radio == 3" label="哪些代理不可见" prop="unviewable">
                <el-input v-model="formData.unviewable" placeholder="请输入哪些代理不可见">
                    <template #append>以英文,分隔开</template>
                </el-input>
            </el-form-item>
        </div>
          <div>
              <el-form-item label="是否自动发货">
                  <el-radio-group v-model="formData.send_type">
                      <el-radio :label="1">自动发货</el-radio>
                      <el-radio :label="2">正常发货</el-radio>
                  </el-radio-group>
              </el-form-item>
          </div>
          <div>
              <el-form-item label="兑换产品">
                  <div class="flex flex-col">
                      <div>
                          <el-radio-group v-model="formData.state_hot">
                              <el-radio :label="1">普通商品</el-radio>
                              <el-radio :label="2">优惠卷</el-radio>
                              <el-radio :label="3">现金红包</el-radio>
                          </el-radio-group>
                      </div>
                      <!--                           <duv style="color: #67C23A">默认为正常商品，选择优惠券后购买该产品订单将会直接完成，对应优惠券直接到账且退款无效</duv>-->
                  </div>
              </el-form-item>
              <el-form-item v-if="formData.state_hot == 3" label="现金兑换金额" prop="goods_rate">
                  <el-input-number v-model="formData.goods_rate" :min="0" :precision="2" :step="0.1" controls-position="right"/>
              </el-form-item>
          </div>
          <div v-if="formData.state_hot == 2">
              <el-form-item label="赠送优惠券数量" prop="gift_coupon_count">
                  <el-input-number v-model="formData.gift_coupon_count" :min="0" :step="1" controls-position="right"/>
              </el-form-item>
              <el-form-item label="赠送优惠券" prop="gift_coupon">
                  <el-select v-model="formData.gift_coupon">
                      <template v-for="(item, index) in eggSelectList.list">
                          <el-option :label="item.name" :value="item.id" />
                      </template>
                  </el-select>
              </el-form-item>
          </div>
        <div>
          <el-form-item label="商品简介描述" prop="remark">
              <div class="w-80">
                  <el-input
                          type="textarea"
                          :autosize="{ minRows: 6, maxRows: 6 }"
                          v-model="formData.remark"
                          maxlength="200"
                          show-word-limit
                          clearable
                          placeholder="请输入商品简介描述"
                  />
              </div>
          </el-form-item>
        </div>
        <div>
            <el-form-item label="商品富文本详情" prop="content">
                <editor v-model="formData.content" :height="400" :width="'100%'" />
            </el-form-item>
        </div>
      </el-form>
      <footer-btns v-perms="['goods.goods/edit', 'goods.goods/add']">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </footer-btns>
    </el-card>
  </div>
</template>
<script lang="ts" setup>

import { useDictOptions } from "@/hooks/useDictOptions";
import type { CheckboxValueType, ElTree, FormInstance } from "element-plus";
import { editEgg, addEgg, detailEgg, getGiveGoodsCouponListToGift } from '@/api/eggManage'
const coverRef = ref(null)  // 封面
const imgRef = ref(null) // 轮播
import useAppStore from "@/stores/modules/app";
import { goodRule } from './data.ts'
import {getCouponList} from "@/api/consumer";
import {ref} from "vue";
import {shopCatListTree} from "@/api/goods";
const route = useRoute();
const router = useRouter();
const formData = reactive({
    second_cat_id: "",
    name: "",
    gift_coupon_count: 0,
    gift_coupon: 0,
    cover: "",
    slider: [],
    price_market: 0,
    price_selling: 0,
    vip_reward_balance2: 0,
    vip_reward_balance2_balance3: 0,
    vip_reward_balance2_inv_rate: 0,
    limit_max_num: 0,
    stock_virtual: 0,
    is_recommend: 1,
    spec_type: 1,
    overlay_coupon: 1,
    daili_viewable_radio: 1,
    remark: "",
    viewable: "",
    unviewable: "",
    data_specs: [],
    data_items: [],
    send_type: 1,
    state_hot: 1,
    goods_rate: 0,
    stock_total: 0,
});

const { optionsData } = useDictOptions<{
    lists: any[]
}>({
    lists: {
        api: shopCatListTree
    }
})

// const { optionsData: classifyList } = useDictOptions<{
//     lists: any[]
// }>({
//     lists: {
//         api: getGiveGoodsCouponListToGift
//     }
// });


// 优惠卷
let { optionsData: couponList } = useDictOptions<{
    lists: any[]
}>({
    lists: {
        api: getCouponList
    }
});


const eggSelectList = ref([]);
getGiveGoodsCouponListToGift().then(res => {
    res.list?.unshift({
        id: 0,
        name: '---- 不选择 ----'
    })
    eggSelectList.value = res;
})



// 照片更新
const actionImg = async (type: string) => {
    console.log(type)
    if (type === 'cover') {
        formData.cover = coverRef.value.fileList[0].response.data.url;
    }
    if (type === 'slider') {
        formData.slider.push(imgRef.value.fileList[0].response.data.url)
    }
};


//保存
const formRef = shallowRef<FormInstance>();
const handleSubmit = async () => {
    await formRef.value?.validate();
    let copyFormData = JSON.parse(JSON.stringify(formData));
    if (route.query.id) {
        copyFormData.code = route.query.code;
        await editEgg(copyFormData);
        router.back();
    } else {
        copyFormData.slider = formData.slider.length ? formData.slider.join('|') : String(formData.slider);
        await addEgg(copyFormData);
        router.back();
    }
};


// 编辑
if (route.query.id) {
    detailEgg({id: route.query.id}).then(res => {
        Object.keys(formData).forEach(key => {
            if (res.hasOwnProperty(key)) {
                if (['second_cat_id', 'price_market', 'price_selling','vip_reward_balance2','vip_reward_balance2_balance3','vip_reward_balance2_inv_rate'].includes(key)) {res[key] = Number(res[key])}
                if (key === 'slider') {res[key] = res[key].split('|')}
                formData[key] = res[key];
                if (res.viewable != '') {
                    formData.daili_viewable_radio = 2
                }
                if (res.unviewable != '') {
                    formData.daili_viewable_radio = 3
                }
            }
        });
    })
}

</script>
<style lang="scss" scope>
.preview {
  width: 375px;
  box-sizing: border-box;
  flex: none;
  height: 722px;
  border: 1px solid hsla(0, 0%, 89.8%, 0.898039);
  display: flex;
  flex-direction: column;
}
.title {
  background: #f5f8ff;
  height: 40px;
  border-bottom: 1px solid hsla(0, 0%, 89.8%, 0.898039);
}
.text-nowrap {
  word-break: break-all;
}
.tableList-check-div {
    border: 1px #B6B6B6 solid;
    box-sizing: border-box;
    padding: 5px;
    cursor: pointer;
}
    .table {
        /*border: 1px red solid;*/
        width: 98%;
        margin: 20px;
        box-sizing: border-box;
        border: 1px solid #B6B6B6;
        border-top: none;
        border-left: none;
        .table-div {
            /*border: 1px red solid;*/
            display: flex;
            flex-direction: row;
            .table-div-item {
                /*border: 1px red solid;*/
                /*flex: 1;*/
                width: calc(100%/8);
                text-align: center;
                /*background-color: #f5f7fa;*/
                border: 1px solid #B6B6B6;
                border-right: none;
                border-bottom: none;
                box-sizing: border-box;
                background-color: #f5f7fa;
                padding: 10px;
            }
        }
        .table-body {
            display: flex;
            flex-direction: row;
            .table-body-item {
                width: calc(100%/8);
                overflow-x: auto;
                text-align: center;
                /*background-color: #f5f7fa;*/
                border: 1px solid #B6B6B6;
                border-right: none;
                border-bottom: none;
                box-sizing: border-box;
                padding: 10px;
            }
        }
    }
</style>
